#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#define MAX_LINE_LENGTH 1024

int main(int argc, char *argv[]) {
	char buffer[MAX_LINE_LENGTH];

	printf("%d",argc);
	if (argc > 1 && argv[1][0] == '<') {

		char filename[500];
		int i=1;
		for(i=1;argv[1][i]!='\0';i++)
		{
			filename[i-1]=argv[1][i];
		}
		filename[i]='\0';

		int fd = open(filename, O_RDONLY);
		if (fd < 0) {    
			perror("open file");;
			return -1;
		}

		int ret = 0;
		do {
			memset(buffer, 0, sizeof(buffer));
			ret = read(fd, buffer, sizeof(buffer));
			if(ret > 0)
				write (1, buffer, ret);
		} while (ret > 0);


		close(fd);
	}

	else if (argc > 1 && argv[1][0] == '>') {

		char filename[500];
		int i=1;
		for(i=1;argv[1][i]!='\0';i++)
		{
			filename[i-1]=argv[1][i];
		}
		filename[i]='\0';

		int fd = open(filename, O_RDWR | O_CREAT | O_TRUNC, 0755);
		if (fd < 0) {
			close(fd);
			perror("open file");
			return -1;
		}

		int ret = 0;
		do {
			memset(buffer, 0, sizeof(buffer));
			ret = read(0, buffer, sizeof(buffer));
			if (ret > 0)
				write(fd, buffer, ret);
		} while (ret > 0);


		close(fd);
	}
	/////ahahahahhhahaa  保存一下

	else {

		if (argc != 1) {

			int fd = open(argv[1], O_RDONLY);
			if (fd < 0) {    
				perror("open file");;
				return -1;
			}

			int ret = 0;
			do {
				memset(buffer, 0, sizeof(buffer));
				ret = read(fd, buffer, sizeof(buffer));
				if(ret > 0)
					write (1, buffer, ret);
			} while (ret > 0);


			close(fd);
		}


		else {
			int ret = 0;
			while (ret = read(0, buffer, sizeof(buffer))) {

				write(1, buffer, ret);
			}
		}
	}

	return 0;
	//asdasdasdadadadsdasdasdasdas
}


